package com.edu.kindergarten.adapter;

import java.util.HashSet;
import java.util.Set;

import android.content.Context;
import android.database.Cursor;
import android.provider.MediaStore;
import android.support.v4.widget.CursorAdapter;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.RelativeLayout.LayoutParams;

import com.edu.kindergarten.config.Constants;
import com.edu.kindergarten.utils.LogUtils;
import com.edu.kindergarten.utils.ScreenUtils;
import com.nostra13.universalimageloader.core.ImageLoader;

public class SingleImageCursorAdapter extends CursorAdapter {

	private static final String TAG = "SingleImageAdapter";

	private Context context;
	private int layoutId;
	private String[] from;
	private int to[];
	private boolean multiSelect = false;
	
	private Set<String> checkedSet;
	private SparseArray<String> itemMap;
	private int imageWidth;
	
	private CheckedChangeListener checkedChangeListener;
	private int mCountAvail = Constants.SELECT_IMAGE_MAX_NUMBER;
	//private Uri imageUriPref = Images.Media.getContentUri("external");
	//private Uri imageThumbUriPref = Images.Thumbnails.getContentUri("external");
	
	private LayoutInflater mInflater;
	private int itemPosition;
	
	public SingleImageCursorAdapter(Context context, 
			int layoutId, Cursor c, String[] from, int[] to) {
		super(context, c, 0);
		this.context = context;
		this.layoutId = layoutId;
		this.from = from;
		this.to = to;
		mInflater = LayoutInflater.from(context);
		
		setDefaultWidth();
	}
	
	public SingleImageCursorAdapter(Context context, 
			int layoutId, Cursor c, String[] from, int[] to,int countAvail) {
		super(context, c, 0);
		this.context = context;
		this.layoutId = layoutId;
		this.from = from;
		this.to = to;
		
		mInflater = LayoutInflater.from(context);
		
		setDefaultWidth();
		
		this.multiSelect = true;
		mCountAvail = countAvail;
		checkedSet = new HashSet<String>();
		itemMap = new SparseArray<String>();
	}
	
	/*public SingleImageCursorAdapter(Context context, int layoutId,
			List<String> listData, int to[],boolean multiSelect,int countAvail) {
		this.context = context;
		this.layoutId = layoutId;
		this.listData = listData;
		this.to = to;
		this.multiSelect = multiSelect;
		mCountAvail = countAvail;
		checkedIdxList = new SparseBooleanArray();
		mInflater = LayoutInflater.from(context);
		
		//we have 3 columns, and each column has left/right border
		imageWidth = ScreenUtils.getScreenWidth(context)/3 - 4*2;
	}*/
	
	private void setDefaultWidth(){
		//we have 3 columns, and each column has left/right border
		imageWidth = ScreenUtils.getScreenWidth(context)/3 - 4*2;
	}
	
	public Set<String> getCheckedSet(){
		return checkedSet;
	}

	public SparseArray<String> getItemMap(){
		return itemMap;
	}
	
	public void setCheckChangeListener(CheckedChangeListener listener){
		checkedChangeListener = listener;
	}
	
	/*@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return listData.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return listData.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}*/
	
	@Override
	public void bindView(View view, Context context, Cursor cursor) {
		// TODO Auto-generated method stub
		LogUtils.d(TAG,"zxj - bindView");
		final ViewHolder holder = (ViewHolder)view.getTag();
		
		if(holder == null){
			LogUtils.d(TAG,"zxj - holder == null");
			return;
		}else {
			String filePath = "";
			try {
				filePath = Constants.filePrefix + cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.DATA));
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
			
			LogUtils.d(TAG,"bindView,filePath:" + filePath);
			itemMap.put(itemPosition, filePath);
			ImageLoader.getInstance().displayImage(filePath, holder.imageView);
			
			if (checkedSet.contains(filePath)) {
				holder.checkBox.setChecked(true);
			}else {
				holder.checkBox.setChecked(false);
			}
			
			final String path = filePath;
			holder.checkBox.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View view) {
					// TODO Auto-generated method stub
					boolean checked = holder.checkBox.isChecked();
					LogUtils.d(TAG, "onCheckedChanged, checkedSet.size():" + checkedSet.size() +
							",checked:" + checked +
							",item position:" + itemPosition +
							",path:" + path);
					if (checked) {
						if (checkedSet.size() < mCountAvail) {
							if (!checkedSet.contains(path)) {
								checkedSet.add(path);
							}
						}else {
							//uncheck checkbox
							holder.checkBox.toggle();
						}
					}else {
						if (checkedSet.contains(path)) {
							checkedSet.remove(path);
						}
					}
					if (checkedChangeListener != null) {
						checkedChangeListener.OnCheckBoxChangeListener(checked,path,checkedSet);
					}
				}
			});
		}
		
		/*try {
			long id = cursor.getLong(cursor.getColumnIndex(MediaStore.Files.FileColumns._ID));
			Uri uri = ContentUris.withAppendedId(imageUriPref, id);
			ImageLoader.getInstance().displayImage(uri.toString(), holder.imageView);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}*/
	}

	@Override
	public View newView(Context context, Cursor cursor, ViewGroup parent) {
		// TODO Auto-generated method stub
		LogUtils.d(TAG,"zxj - newView");
		View convertView = mInflater.inflate(layoutId,parent,false);
		final ViewHolder holder = new ViewHolder();
		holder.imageView = (ImageView) convertView.findViewById(to[0]);
		LayoutParams params = new LayoutParams(imageWidth, imageWidth);
		holder.imageView.setLayoutParams(params);
		
		if (multiSelect) {
			holder.checkBox = (CheckBox) convertView.findViewById(to[1]);
			
			/*String filePath = "";
			try {
				filePath =  pathPref + cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.DATA));
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
			
			LogUtils.d(TAG,"newView,filePath:" + filePath);
			itemMap.put(itemPosition, filePath);*/
			/*holder.checkBox.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View view) {
					// TODO Auto-generated method stub
					boolean checked = holder.checkBox.isChecked();
					String path = itemMap.get(itemPosition);
					LogUtils.d(TAG, "onCheckedChanged, checkedSet.size():" + checkedSet.size() +
							",checked:" + checked +
							",item position:" + itemPosition +
							",path:" + path);
					if (checked) {
						if (checkedSet.size() < mCountAvail) {
							if (!checkedSet.contains(path)) {
								checkedSet.add(path);
							}
						}else {
							//uncheck checkbox
							holder.checkBox.toggle();
						}
					}else {
						if (checkedSet.contains(path)) {
							checkedSet.remove(path);
						}
					}
					if (checkedChangeListener != null) {
						checkedChangeListener.OnCheckBoxChangeListener(checked,path,checkedSet);
					}
				}
			});*/
			/*holder.checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
				
				@Override
				public void onCheckedChanged(CompoundButton arg0, boolean checked) {
					// TODO Auto-generated method stub
					
					LogUtils.d(TAG, "onCheckedChanged, checkedSet.size():" + checkedSet.size() +
							",checked:" + checked +
							",path:" + path);
					if (checked) {
						if (checkedSet.size() < mCountAvail) {
							if (!checkedSet.contains(path)) {
								checkedSet.add(path);
							}
						}else {
							//uncheck checkbox
							holder.checkBox.toggle();
						}
					}else {
						if (checkedSet.contains(path)) {
							checkedSet.remove(path);
						}
					}
					if (checkedChangeListener != null) {
						checkedChangeListener.OnCheckBoxChangeListener(checked,path,checkedSet);
					}
				}
			});*/
			
			/*Uri uri = null;
			try {
				long id = cursor.getLong(cursor.getColumnIndex(MediaStore.Files.FileColumns._ID));
				uri = ContentUris.withAppendedId(imageUriPref, id);
				
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
			
			final String key = uri != null ? uri.toString() : null;*/
		}
		convertView.setTag(holder);
		
		return convertView;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		LogUtils.d(TAG,"zxj - getView,position:" + position);
		itemPosition = position;
		return super.getView(position, convertView, parent);
	}

	public class ViewHolder {
		public ImageView imageView;
		public CheckBox checkBox;
	}
	
	public interface CheckedChangeListener {
		public void OnCheckBoxChangeListener(boolean checked,String key,Set checkedSet);
	}

}
